package com.xxl.job.admin.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.xxl.job.admin.core.model.XxlJobRegistry;
import com.xxl.job.admin.core.util.DateUtil;
import com.xxl.job.admin.dao.XxlJobRegistryDao;
import com.xxl.job.admin.service.XxlJobRegistryService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import static com.xxl.job.admin.core.model.table.Tables.XXL_JOB_REGISTRY;

@Service
public class XxlJobRegistryServiceImpl extends ServiceImpl<XxlJobRegistryDao, XxlJobRegistry> implements XxlJobRegistryService {
    @Override
    public List<XxlJobRegistry> findAll(int deadTimeout, Date date) {
        QueryWrapper q= QueryWrapper.create()
                .from(XXL_JOB_REGISTRY)
                .where("update_time > DATE_ADD('"+DateUtil.getDateFormat(date)+"',INTERVAL -"+deadTimeout+" SECOND)");
        return list(q);
    }

    @Override
    public List<Integer> findDead(int deadTimeout, Date date) {

        QueryWrapper q= QueryWrapper.create()
                .select(XXL_JOB_REGISTRY.ID)
                .from(XXL_JOB_REGISTRY)
                .where("update_time < DATE_ADD('"+ DateUtil.getDateFormat(date)+"',INTERVAL -"+deadTimeout+" SECOND)");
        return listAs(q,Integer.class);
    }
    @Override
    public int registryUpdate(String registryGroup, String registryKey, String registryValue, Date updateTime) {
       boolean x= UpdateChain.of(XxlJobRegistry.class)
                .set(XXL_JOB_REGISTRY.UPDATE_TIME,updateTime)
                .where(XXL_JOB_REGISTRY.REGISTRY_GROUP.eq(registryGroup))
                .and(XXL_JOB_REGISTRY.REGISTRY_KEY.eq(registryKey))
                .and(XXL_JOB_REGISTRY.REGISTRY_VALUE.eq(registryValue))
                .update();
        return x?1:0;
    }

    @Override
    public void registrySave(String registryGroup, String registryKey, String registryValue, Date date) {
        XxlJobRegistry xxlJobRegistry = new XxlJobRegistry();
        xxlJobRegistry.setRegistryGroup(registryGroup);
        xxlJobRegistry.setRegistryKey(registryKey);
        xxlJobRegistry.setRegistryValue(registryValue);
        xxlJobRegistry.setUpdateTime(date);
        save(xxlJobRegistry);
    }
    @Override
    public int registryDelete(String registryGroup, String registryKey, String registryValue) {
        QueryWrapper q= QueryWrapper.create()
                .where(XXL_JOB_REGISTRY.REGISTRY_GROUP.eq(registryGroup))
                .and(XXL_JOB_REGISTRY.REGISTRY_KEY.eq(registryKey))
                .and(XXL_JOB_REGISTRY.REGISTRY_VALUE.eq(registryValue));
        boolean i= remove(q);
         return i?1:0;
    }
}
